﻿using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Azure.Core;
using BlogSystem.Common.Config.DI.annotation;
using BlogSystem.Model.Respones;
using Microsoft.IdentityModel.Tokens;

namespace BlogSystem.Common.Util;

/// <summary>
/// 授权JWT
/// </summary>
///
[Ioc("scoped")]
public class JWTHelper
{
// 配置 读取 .json 文件当中 信息
        private readonly IConfiguration _configuration;
        private readonly IHttpContextAccessor _httpContextAccessor;
        /// <summary>
        /// Token配置
        /// </summary>
        /// <param name="configuration"></param>
        public JWTHelper(IConfiguration configuration,IHttpContextAccessor httpContextAccessor)
        {
            _configuration = configuration;
            _httpContextAccessor = httpContextAccessor;
        }
 
        /// <summary>
        /// 创建Token 这里面可以保存自己想要的信息,后续可用直接传整个对象进来
        /// </summary>
        /// <param name="username"></param>
        /// <param name="phone"></param>
        /// <param name="userid"></param>
        /// <returns></returns>
        public LoginResponse CreateToken(string username,string phone,int userid)
        {
            // 1. 定义需要使用到的Claims
            var claims = new[]
            {
            new Claim("username", username),
            new Claim("phone", phone),
            new Claim("id", userid+""),

            /* 可以保存自己想要信息，传参进来即可
            new Claim("limit", "limit"),
            new Claim("head_url", "xxxxx")
            */
        };
        
            // 2. 从 appsettings.json 中读取SecretKey
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"]));
 
            // 3. 选择加密算法
            var algorithm = SecurityAlgorithms.HmacSha256;
 
            // 4. 生成Credentials
            var signingCredentials = new SigningCredentials(secretKey, algorithm);
 
            // 5. 根据以上，生成token
            var jwtSecurityToken = new JwtSecurityToken(
                _configuration["Jwt:Issuer"],    //Issuer
                _configuration["Jwt:Audience"],  //Audience
                claims,                          //Claims,
                DateTime.Now,                    //notBefore
                DateTime.Now.AddHours(5),     //expires
                signingCredentials               //Credentials
            );
 
            // 6. 将token变为string[序列化]
            var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
            // 封装token 或者 直接返回
            var data = new LoginResponse
            {
                Expires = DateTime.Now.AddHours(5)
            };
            data.Token =token;
            data.Username = username;
            return data;
        }

        
        
}
 
    
